package com.scalar.chiptrack.adaptor.smic;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.ParserException;
import com.scalar.chiptrack.adaptor.FabSortLot;
import com.scalar.chiptrack.adaptor.ShippedLot;
import com.scalar.chiptrack.adaptor.gtc.GTCSortBinReport;
import com.scalar.chiptrack.adaptor.utils.ParserResult;
import com.scalar.chiptrack.adaptor.utils.Parser;
import com.scalar.chiptrack.adaptor.utils.ParserFactory;
import com.scalar.chiptrack.adaptor.utils.XLSParserImpl;
import com.scalar.chiptrack.adaptor.dao.FabSortAdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.adaptor.dao.ShippedLotDAO;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.ScalarException;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Date;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: Sudhakar
 * Date: May 1, 2007
 * Time: 4:01:25 PM
 */
public class SMICDataParser extends JobHandler implements AdaptorConstants
{
    private HashMap<String, FabSortLot> m_fabwipDataMap    = new HashMap<String, FabSortLot>();
    private HashMap<String, FabSortLot> m_sortwipDataMap   = new HashMap<String, FabSortLot>();
    private HashMap<String, ShippedLot> m_fabshipDataMap   = new HashMap<String, ShippedLot>();
    private HashMap<String, ShippedLot> m_sortshipDataMap  = new HashMap<String, ShippedLot>();
    private HashMap<String, FabSortLot> m_sortBinDataMap   = new HashMap<String, FabSortLot>();

    private static Logger m_parserLogger    = null;
    private String m_dataOutputDir          = null;

    int m_waferQtyIn            = 0;
    int m_totalPassQty          = 0;
    float m_totalYield          = 0.0f;
    public SMICDataParser() throws ScalarException
    {
        try
        {
            m_dataOutputDir = AdaptorUtils.getDataOutputDir(VENDOR_NAME_SMIC, WIP_TYPE_FAB);
            AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
            
            m_parserLogger = AdaptorUtils.getDataParserLogger( m_dataOutputDir,VENDOR_NAME_SMIC );
            FabSortAdaptorDAO.setLogger(m_parserLogger);
            ShippedLotDAO.setLogger( m_parserLogger );
            AdaptorUtils.setLogger(m_parserLogger);
        }
        catch (ScalarException se)
        {
            log("ERROR!! ERROR!! ERROR!! Exception while loading SMIC WIP output directory details from database, Exception: " + se);
            throw se;
        }
    }
    /**
     *
     * @param args
     * @throws Exception
     */
    public static void main(String args[]) throws Exception
    {
        new SMICDataParser().execute();
    }
    /**
     *
     * @throws Exception
     */
    public void execute() throws Exception
    {
        AdaptorUtils.printHeader(VENDOR_NAME_SMIC, CONSTANT_PARSER);

        File doneDestDir = new File( m_dataOutputDir + "/done" );

        File smicWipDataoutDir = new File(m_dataOutputDir);


        File[] fileList = smicWipDataoutDir.listFiles();

        if ((fileList == null) || (fileList.length <= 3))
        {
            log("No file found in directory: " + smicWipDataoutDir);
            throw new ScalarException("No file found in directory: " + smicWipDataoutDir + "----\n\n");
        }

        ArrayList<File> successFileList   = new ArrayList<File>();
        boolean success             = true;

        try
        {
            for (int i = 0; i < fileList.length; i++)
            {

                if (fileList[i].isDirectory() == true)
                {
                    continue;
                }

                if ((fileList[i].getName() != null) && (fileList[i].getName().trim().startsWith(SMICFtpAdaptor.FILE_NAME_SMIC_WIP)))
                {
                    try
                    {
                        ArrayList<SMICWipStatus> m_smicWipList = parseWipInfo( fileList[i].getAbsolutePath() );
                        if (m_smicWipList != null)
                        {
                            getSMICWipList(m_smicWipList);
                        }
                        successFileList.add(fileList[i]);
                    }
                    catch (Exception e)
                    {
                        success = false;
                        log("Exception while parsing and storing file: " + fileList[i].getAbsolutePath() + "\nException: " + e);
                        e.printStackTrace();
                        throw e;
                    }
                }
				
                if ((fileList[i].getName() != null) && (fileList[i].getName().trim().startsWith(SMICPOP3Adaptor.SHIP_FILE_NAME)))
                {
                    try
                    {
                        parseShipReport( fileList[i].getAbsolutePath() );

                        successFileList.add(fileList[i]);
                    }
                    catch (Exception e)
                    {
                        success = false;
                        log("Exception while parsing and storing file: " + fileList[i].getAbsolutePath() + "\nException: " + e);
                        e.printStackTrace();
                        throw e;
                    }
                }

                if ((fileList[i].getName() != null) && (fileList[i].getName().trim().startsWith(SMICPOP3Adaptor.BIN_FILE_NAME )))
                {
                    try
                    {
                        ArrayList sortlotbinList = parseSortLotBinReport( fileList[i].getAbsolutePath() );


                        //To get the Sort Binning information
                        getSortBinDetails( sortlotbinList );

                        successFileList.add(fileList[i]);
                    }
                    catch (Exception e)
                    {
                        success = false;
                        log("Exception while parsing and storing file: " + fileList[i].getAbsolutePath() + "\nException: " + e);
                        e.printStackTrace();
                        throw e;
                    }
                }

            }
        }
        catch (Exception e)
        {
            success = false;
            log("ERROR!! ERROR!! ERROR!! While parsing and storing File " + e);
            e.printStackTrace();
            throw e;
        }
       // to save the Fab lot tables
        try
        {
            if ( m_fabwipDataMap.isEmpty() == false )
            {
                log( "Updating Fab Lot Information" );
                FabSortAdaptorDAO.saveFabLot( null,  m_fabwipDataMap.values().iterator(), WIP_TYPE_FAB, VENDOR_NAME_SMIC );
            }
            else
            {
                System.out.println( "This is FAB Data Parser FAB Part Number List is empty" );
                FabSortAdaptorDAO.closeFabSortLot( null, WIP_TYPE_FAB, VENDOR_NAME_SMIC );
            }

             // Save shipping info -
            if ( m_fabshipDataMap.isEmpty() == false )
            {
                log( "Updating shipment Information" );
                ShippedLotDAO.saveShippedLot( null, m_fabshipDataMap.values().iterator() );
            }
        }
        catch ( Exception e )
        {
            success = false;
            log( "ERROR!! ERROR!! ERROR!! Could not update Fab Data information into database: " + e );
            e.printStackTrace();
            throw e;
        }
        try
        {
            if ( m_sortBinDataMap.isEmpty() == false )
            {
                FabSortAdaptorDAO.saveSortBinData( null, m_sortBinDataMap.values().iterator() );
            }
            success = true;
            m_sortBinDataMap.clear();
        }
        catch(Exception e)
        {
            success = false;
            System.out.println(" Exception Occrred While Saving the Sort Binning Info " +e );
            throw e;
        }
        try
        {
            if ( m_sortwipDataMap.isEmpty() == false )
            {
                log( "Updating SORT Lot Information" );
                FabSortAdaptorDAO.saveSortLot( null, m_sortwipDataMap.values().iterator(), WIP_TYPE_SORT, VENDOR_NAME_SMIC );
            }
            else
            {
                System.out.println( "This is FAB Data Parser SORT Part Number List is empty" );
                FabSortAdaptorDAO.closeFabSortLot( null, WIP_TYPE_SORT, VENDOR_NAME_SMIC );
            }

            // Save shipping info -
            if ( m_sortshipDataMap.isEmpty() == false )
            {
                log( "Updating shipment Information" );
                ShippedLotDAO.saveShippedLot( null, m_sortshipDataMap.values().iterator() );
            }
        }
        catch ( Exception e )
        {
            success = false;
            log( "ERROR!! ERROR!! ERROR!! Could not update SORT Data information into database: " + e );
            e.printStackTrace();
            throw e;
        }


        // To Close the Drop Out Lots
        AdaptorDAO.closeDropOutLots(VENDOR_NAME_SMIC);

        // TO SEND THE NEW LOTS, NEW TRANSIT LOTS, NO PO LOTS, DISCREPANCY LOTS NOTIFICATIONS TO THE USER
        AdaptorDAO.sendAllNotifications(VENDOR_NAME_SMIC, true, true, true);


        int adaptor_id = AdaptorRunInfo.getLastRunAdaptorId( SMICPOP3Adaptor.ADAPTOR_NAME, CONSTANT_ADAPTOR);

        // Update Adaptor_Run_Info table
        try
        {
            if ( success == true )
            {
                AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, SMICPOP3Adaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
                System.out.println( "SUCCESSFULLY UPDATED IN THE DATABASE" );
            }
        }
        catch ( ScalarException se )
        {
            success = false; //As filES DATA SAVED , UPDATEING AS SUCCESS
            AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, SMICPOP3Adaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
            log( "WARNING!! WARNING!! WARNING!! Could not update Adaptor run information, Exception: " + se );
            throw se;
        }
        // Move the successful files to 'done' directory
        if (success)
        {
            AdaptorUtils.moveFilesToDone(successFileList, doneDestDir);
        }
    }
    /**
     *
     * @param fileName
     * @return
     * @throws Exception
     */
    private ArrayList<SMICWipStatus> parseWipInfo(String fileName) throws Exception
    {
        if (fileName == null) throw new ScalarException("Filename argument is null");

        ArrayList wipInfoList       = new ArrayList();
        BufferedReader fileReader   = null;

        try
        {
            File wipInfoFile = new File(fileName);
            if (wipInfoFile.exists() == false)
            {
                throw new ScalarException(fileName + " doesnt exist");
            }

            System.out.println("Found " + fileName);
            System.out.println("Parsing the file for Product Information...");

            fileReader = new BufferedReader(new FileReader(wipInfoFile));

            String line = null;
            SMICWipStatus wipInfo = null;
            ArrayList errors = new ArrayList();

            for( int i = 0; i<5; i++)
            {
                fileReader.readLine();  // skip 5 lines
            }

            while ((line = fileReader.readLine()) != null)
            {
                try
                {
                    wipInfo = parseWipInfoLine(line);
                }
                catch (ParserException pe)
                {
                    wipInfo = null;
                    errors.add(pe.getMessage());
                }
                if (wipInfo != null)
                {
                    wipInfoList.add(wipInfo);
                }
            }

            fileReader.close();
            fileReader = null;

            System.out.println("Done parsing..");

            if (errors.isEmpty() == false)
            {
                System.out.println("\nFound errors... notifying system administrator...");
                System.out.println("done\n");
            }
        }
        finally
        {
            if (fileReader != null)
            {
                try
                {
                    fileReader.close();
                }
                catch (IOException ignore) {
                }
            }
        }

        return wipInfoList;
    }
    /**
     *
     * @param line
     * @return
     * @throws ParserException
     */
    private SMICWipStatus parseWipInfoLine(String line) throws ParserException
    {

        SMICWipStatus wipInfo = null;

        if ((line == null) || (line.startsWith("---")) || (line.trim().length() < 65 /*min length*/))
        {
            return wipInfo;
        }

        try
        {
            String[] token = line.split(",");

            wipInfo = new SMICWipStatus();

            for (int x = 0; x < token.length; x++)
            {
                if (token[x] != null && token[x].trim().length() > 0)
                {
                    switch (x)
                    {
                        case 0:
                            wipInfo.setProductID(token[x].trim());
                            break;
                        case 1:
                            wipInfo.setCustomerDevice(token[x].trim());
                            break;
                        case 2:
                            wipInfo.setPoNumber(token[x].trim());
                            break;
                        case 3:
                            wipInfo.setLotID(token[x].trim());
                            break;
                        case 4:
                            wipInfo.setLotStatus(token[x].trim());
                            break;
                        case 5:
                            wipInfo.setStage(token[x].trim());
                            break;
                        case 6:
                            wipInfo.setStepTrackinDate(token[x].trim());
                            break;
                        case 7:
                            wipInfo.setCurrentWaferQty(token[x].trim());
                            break;
                        case 8:
                            wipInfo.setProjectedOutDate(token[x].trim());
                            break;
                        case 9:
                            wipInfo.setCommitDate(token[x].trim());
                            break;
                        case 10:
                            wipInfo.setWaferStartDate(token[x].trim());
                            break;
                      /*  case 11:
                            wipInfo.setTotalSteps(token[x].trim());
                            break;
                        case 12:
                            wipInfo.setRemSteps(token[x].trim());
                            break;*/
                        case 11:
                            wipInfo.setTotalLayers(token[x].trim());
                            break;
                        case 12:
                            wipInfo.setRemLayers(token[x].trim());
                            break;
                        case 13:
                            wipInfo.setSmicFab(token[x].trim());
                            break;
                        case 14:
                            wipInfo.setGoodDieQty(token[x].trim());
                            break;
                    }
                }
            }
        }
        catch (Exception e)
        {
            System.out.println("Exception while parsing Wip Info: " + e);
            System.out.println("Line: " + line);
            throw new ParserException("Exception while parsing Wip Info: " + e + "\nLine: " + line, e);
        }

        return wipInfo;
    }
    /**
     *
     * @param wipdataList
     */
    public void getSMICWipList(ArrayList wipdataList) throws Exception
    {
        SMICWipStatus smicWipReport = null;
        String partNumber           = null;
        String lotNumber            = null;
        FabSortLot fabSortLot       = null;

        Iterator iterator = wipdataList.iterator();
        while (iterator.hasNext())
        {
            smicWipReport = (SMICWipStatus) iterator.next();

            if (smicWipReport != null )
            {
                partNumber = smicWipReport.getProductID();
                lotNumber = smicWipReport.getLotID();
				
				if (partNumber.indexOf("-") != -1 )
				{
					partNumber = partNumber.substring(0, partNumber.lastIndexOf("-") );
				}

                if ( "CP".equalsIgnoreCase(smicWipReport.getSmicFab() ) )
                {
                    fabSortLot = ( FabSortLot ) m_sortwipDataMap.get( partNumber + lotNumber );
                    if ( fabSortLot == null )
                    {
                        fabSortLot = new FabSortLot(VENDOR_NAME_SMIC, WIP_TYPE_SORT );
                        m_sortwipDataMap.put( partNumber + lotNumber , fabSortLot );
                    }
                }
                else
                {

                    fabSortLot = ( FabSortLot ) m_fabwipDataMap.get( partNumber + lotNumber );
                    if ( fabSortLot == null )
                    {
                        fabSortLot = new FabSortLot(VENDOR_NAME_SMIC, WIP_TYPE_FAB );
                        m_fabwipDataMap.put( partNumber + lotNumber , fabSortLot );
                    }
                }

                int quantity = 0;
                if (fabSortLot.getQtyIn() != null)
                {
                    try
                    {
                        quantity = Integer.parseInt(fabSortLot.getQtyIn());
                    }
                    catch (NumberFormatException ignore) {
                    }
                    try
                    {
                        quantity += Integer.parseInt(smicWipReport.getCurrentWaferQty());
                    }
                    catch (NumberFormatException ignore) {
                    }
                }
                else
                {
                    try
                    {
                        quantity = Integer.parseInt(smicWipReport.getCurrentWaferQty());
                    }
                    catch (NumberFormatException ignore) {
                    }
                }
                if ( quantity > 0 )
                {
                    fabSortLot.setLotId(lotNumber);
                    fabSortLot.setCustProduct(partNumber);
                    fabSortLot.setDateIn(StringUtils.formatDate(smicWipReport.getWaferStartDate(), "yyyy-MM-dd", "MM/dd/yyyy"));
                    fabSortLot.setForcastedDateOut(StringUtils.formatDate(smicWipReport.getProjectedOutDate(), "yyyy-MM-dd", "MM/dd/yyyy") ) ;
                    fabSortLot.setOutLookDate(StringUtils.formatDate( smicWipReport.getCommitDate(), "yyyy-MM-dd", "MM/dd/yyyy" ) );
                    fabSortLot.setQtyIn(quantity + "");
                    fabSortLot.setStage(smicWipReport.getStage());
                    fabSortLot.setFabId( smicWipReport.getSmicFab() );
                    fabSortLot.setFabLotNumber(lotNumber);
                    if ( smicWipReport != null && smicWipReport.getLotStatus().equalsIgnoreCase("Hold") )
                    {
                        fabSortLot.setLotStatus(LOT_STATUS_HOLD);
                    }
                    else
                    {
                        fabSortLot.setLotStatus(LOT_STATUS_RUNNING);
                    }
                    fabSortLot.setPoNumber(smicWipReport.getPoNumber());
                }
            }
        }
    }

    private void parseShipReport( String fileName ) throws Exception
    {
        if ( fileName == null ) throw new ScalarException( "Filename argument is null" );

        ParserResult result     = null;
        ShippedLot shippedLot   = null;
        String lotNumber        = null;
        String partNumber       = null;
        String shipDate         = null;
        String nextLocation     = null;
        try
        {
            File shipFile = new File( fileName );
            if ( shipFile.exists() == false )
            {
                throw new ScalarException( fileName + " doesnt exist" );
            }

            log( "\nFound " + fileName );
            log( "Parsing the file for Shipment Report..." );
            System.out.println( "\nFound " + fileName );
            System.out.println( "Parsing the file for Shipment Report..." );

            Parser parser = ParserFactory.getXLSParser( shipFile );

            ((XLSParserImpl)parser).setHeaderRowIdx(0);
            ((XLSParserImpl)parser).setDataStartRowIdx(1);

            result = parser.parse();

            //System.out.println("result.GetHeadisings() = " + result.getHeadings());
            while ( result.next() )
            {
                partNumber = result.getString("Material");
                lotNumber = result.getString("Batch");

                shipDate   =   StringUtils.formatDateToString(result.getDate("Bill_Date"), "MM/dd/yyyy HH:mm:ss" ); // giving as MM/dd/yyyy
                nextLocation = result.getString("Ship_To");

                if ( partNumber != null && partNumber.trim().length() >0 && lotNumber != null && lotNumber.trim().length() > 0 )
                {
                    if (partNumber.indexOf("-") != -1 )
                    {
                        partNumber = partNumber.substring(1, partNumber.lastIndexOf("-") );
                    }
					else
					{
						partNumber = partNumber.substring(1, partNumber.length() );
					}
					
                   if (result.getString("GoodDieCount") != null && result.getInt("GoodDieCount") > 0 )
                   {
                       shippedLot = (ShippedLot) m_sortshipDataMap.get(partNumber + lotNumber + shipDate + nextLocation + result.getString("PO number") );
                        if (shippedLot == null)
                        {
                            shippedLot = new ShippedLot(VENDOR_NAME_SMIC, LOCATION_TYPE_SORT );
                            m_sortshipDataMap.put(partNumber + lotNumber + shipDate+ nextLocation+ result.getString("PO number"), shippedLot);
                        }
                   }
                   else
                   {
					  
                        shippedLot = (ShippedLot) m_fabshipDataMap.get(partNumber + lotNumber + shipDate + nextLocation+ result.getString("PO number"));
                        if (shippedLot == null)
                        {
                            shippedLot = new ShippedLot(VENDOR_NAME_SMIC, LOCATION_TYPE_FAB);
                            m_fabshipDataMap.put(partNumber + lotNumber + shipDate+ nextLocation+ result.getString("PO number"), shippedLot);
                        }
                   }


                    int quantity = 0;
                    if ( shippedLot.getShipQty() != null )
                    {
                       try
                       {
                           quantity = Integer.parseInt( shippedLot.getShipQty() );
                       }
                       catch ( NumberFormatException ignore )
                       {
                           quantity = 0;
                       }
                       try
                       {
                           quantity += result.getInt("SKU qty");
                       }
                       catch ( NumberFormatException ignore )
                       {
                           quantity = 0;
                       }
                    }
                    else
                    {
                       try
                       {
                           quantity = result.getInt("SKU qty");
                       }
                       catch ( NumberFormatException ignore )
                       {
                           quantity = 0;
                       }
                    }
                    if ( quantity > 0 )
                    {
                        shippedLot.setLotNumber( lotNumber );
                        shippedLot.setPartNumber( partNumber );
                        shippedLot.setShipDate( shipDate );
                        shippedLot.setShipQty( quantity + "");
                        shippedLot.setWaferID( result.getString("WaferID") != null ? result.getString("WaferID").replaceAll(",",";") : null );
                        shippedLot.setCustomerPO( result.getString("PO number") !=null && result.getString("PO number").indexOf(".") != -1 ? result.getString("PO number").substring(0,result.getString("PO number").indexOf(".")) : result.getString("PO number") );
                        shippedLot.setShippingDoc( result.getString("Reference_Doc.") );
                        shippedLot.setInvoiceNumber( result.getString("Bill_Doc") );
                        shippedLot.setShipDieQty( result.getString("GoodDieCount") != null && result.getString("GoodDieCount").indexOf(".") != -1 ? result.getString("GoodDieCount").substring(0, result.getString("GoodDieCount").indexOf(".") ) : result.getString("GoodDieCount") );
                        shippedLot.setNextLocation( (nextLocation != null && nextLocation.indexOf(".") != -1 ) ? nextLocation.substring(0, nextLocation.indexOf(".")) : nextLocation );
                        shippedLot.setFabLotNumber( lotNumber );
                    }
                }
            }
        }
        catch ( Exception ex )
        {
            ex.printStackTrace();
            throw ex;
        }
    } // end of prase parseShipReport method



    private ArrayList parseSortLotBinReport( String fileName ) throws Exception
    {
        ArrayList lotbinList = new ArrayList();
        GTCSortBinReport sortBinReport = null;
        if ( fileName == null ) throw new ScalarException( "Filename argument is null" );

        // Phase-I variables
        File lotbinFile = new File( fileName );
        if ( lotbinFile.exists() == false )
        {
            throw new ScalarException( fileName + " doesnt exist" );
        }

        //System.out.println("fileName = " + fileName);

		System.out.println("Found " + fileName);
        System.out.println("Parsing the file for Binning Information...");

        String LOTNO    = "Lot ID :";
        String WAFER_QTY_IN = "Wafer Count :";
        String GOOD_DIE = "Total Good Dies :";
        
        String deviceName = null;

        String lotNo = null;
        String line = null;

        BufferedReader bReader = null;
        try
        {
            bReader = new BufferedReader( new FileReader( lotbinFile ) );

            while ( ( line = bReader.readLine() ) != null )
            {
                line = line.trim();
                //System.out.println("line = " + line);
                if ( line.startsWith("----------") )
                {
                    break;
                }

                if ( line.indexOf( LOTNO ) != -1 )
                {
                    lotNo = line.substring( LOTNO.length() ).trim();
                    //System.out.println("lotNo = " + lotNo);
                }
                            
            }
            bReader.close();
            bReader = null;
            line = null;

            deviceName = AdaptorDAO.getPartNumberByLotNo( lotNo, LOCATION_TYPE_SORT );
            if ( deviceName == null || deviceName.trim().length() == 0 )
            {
                deviceName = AdaptorDAO.getPartNumberByLotNo( lotNo, LOCATION_TYPE_FAB );
            }
            //System.out.println("deviceName = " + deviceName);
            
            bReader = new BufferedReader( new FileReader( lotbinFile ) );
            while ( ( line = bReader.readLine() ) != null  )
            {
                line = line.trim();
                if ( line.indexOf( "|TTl" ) != -1 )
                {
                    m_totalYield = Float.parseFloat(line.substring(11, 16).trim());
                }
                if ( line.indexOf( WAFER_QTY_IN ) != -1 )
                {
                    m_waferQtyIn = Integer.parseInt( line.substring( WAFER_QTY_IN.length() ).trim() );
                    //System.out.println("m_waferQtyIn = " + m_waferQtyIn);
                }
                if ( line.indexOf( GOOD_DIE ) != -1 )
                {
                    m_totalPassQty = Integer.parseInt( line.substring( GOOD_DIE.length() ).trim() );
                    //System.out.println("m_totalPassQty = " + m_totalPassQty );
                }

            }
            bReader.close();
            bReader = null;
            line = null;
                     

            bReader = new BufferedReader( new FileReader( lotbinFile ) );
             //Reading the To Two Lines
            bReader.readLine();
            bReader.readLine();
            while ( ( line = bReader.readLine() ) != null )
            {
                line = line.trim();
                //System.out.println("START line = " + line);

                if ( line.startsWith("Wafer Count") )
                {
                    break;
                }
                if ( line.length() > 0 && ( !line.startsWith( "|WAF" ) ) && ( !line.startsWith( "|NO." ) ) && ( !line.startsWith( "|---" ) )
                        && (!line.startsWith("----------")) && ( !line.startsWith( "|TTl" ) ) )
                {
                    //System.out.println("line = " + line );

                    sortBinReport = new GTCSortBinReport();

                    int waferId = Integer.parseInt( line.substring( 1, 4 ).trim()  );

                    //System.out.println("waferId = " + waferId);
                    //System.out.println("line.substring(6, 10).trim() = " + line.substring(6, 10).trim());
                    //System.out.println("ine.substring(11, 16).trim() = " + line.substring(11, 16).trim());
                    int bin1QtyIn = Integer.parseInt(line.substring(6, 10).trim()); //TOTAL PASS IS TAKING AS BIN1 QTY

                    //System.out.println("bin1QtyIn = " + bin1QtyIn);


                    float waferYield = Float.parseFloat(line.substring(11, 16).trim());
                    //System.out.println("waferYield = " + waferYield);



                    if( lotNo != null && deviceName != null && waferId > 0 && waferId < 26 )
                    {
                        sortBinReport.setWaferId( waferId +"" );
                        sortBinReport.setGoodBinQty( bin1QtyIn );
                        sortBinReport.setDeviceName( deviceName );
                        sortBinReport.setDateIn( DateUtil.formatDate(new Date(), "MM/dd/yyyy") );
                        sortBinReport.setLotNumber( lotNo );

                        sortBinReport.setWaferYield( waferYield );

                        lotbinList.add(sortBinReport);
                    }
                }

            } //END OF WHILE
        }
        catch ( Exception e )
        {
            System.out.println( "Exception while parsing SMIC Sort Bin information \n" + e + "\n" );
            throw e;
        }
        finally
        {
            if ( bReader != null )
            {
                try
                {
                    bReader.close();
                }
                catch ( IOException ignore )
                {
                }
            }
        }
        return lotbinList;
    } // end of prase sortLot bin report method

    private void getSortBinDetails( ArrayList sortBinList )  throws Exception
    {
        if ( sortBinList == null || sortBinList.size() == 0 )
        {
           log( "No Sort Bin Lots when the List is Empty");
           return;
        }
        GTCSortBinReport sortbinReport  = null;
        String partNumber                = null;
        String lotNumber                 = null;
        String waferId                   = null;
        FabSortLot sortBinLot            = null;

        try
        {
            Iterator iterator = sortBinList.iterator();

            while ( iterator.hasNext() )
            {
                sortbinReport = (GTCSortBinReport )iterator.next() ;

                lotNumber  = sortbinReport.getLotNumber();
                waferId    = sortbinReport.getWaferId();
                partNumber = sortbinReport.getDeviceName();

                if ( partNumber != null && lotNumber != null && waferId != null )
                {
                   sortBinLot = ( FabSortLot ) m_sortBinDataMap.get( partNumber + lotNumber + waferId);

                    if ( sortBinLot == null )
                    {
                        sortBinLot = new FabSortLot( VENDOR_NAME_SMIC, LOCATION_TYPE_SORT );
                        m_sortBinDataMap.put( partNumber + lotNumber + waferId  , sortBinLot );
                    }

                    sortBinLot.setCustProduct( partNumber );
                    sortBinLot.setLotId( lotNumber );
                    sortBinLot.setWaferID( waferId );
                     // WAFER QTY IN Always Same(total wafers) ,But For Each every Wafer update the Wafer Qty, the the WaferQty
                    sortBinLot.setQtyIn( m_waferQtyIn +"" );
                    sortBinLot.setDateIn( sortbinReport.getDateIn() );
                    sortBinLot.setTotalgoodDieQtyIn( m_totalPassQty );

                    //sortBinLot.setTesterNo( sortbinReport.getTester());
                    //sortBinLot.setTestProgram( sortbinReport.getTestPgm() );
                    sortBinLot.setGoodDieQtyIn(sortbinReport.getGoodBinQty());
                    sortBinLot.setRejectedQtyIn(sortbinReport.getRejectedQty() );
                    sortBinLot.setShipYield(sortbinReport.getWaferYield()+"");
                    sortBinLot.setTotalYield( m_totalYield ); // if sets as 0, in the PROC Yield Calculating (INQTY *100.00/OUTQTY)
                    sortBinLot.setBinNumber( "Bin1" );
               }
            }
        }
        catch(Exception e )
        {
            throw new ScalarException("Exception occured while parsing the Sort Bin Inforamtion" +e );
        }
    }
    /**
     *
     * @param message
     */
    private static void log(String message)
    {

        if (message == null) return;

        if (m_parserLogger != null)
        {
            synchronized (m_parserLogger)
            {
                m_parserLogger.logDebug(message + LINE_SEPARATOR);
            }
        }
        else
        {
            System.out.println(message);
        }
    }
 
}
